package cn.iocoder.yudao.module.engine.dal.redis.engine;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.engine.model.context.EngineSynStatusCacheContext;
import cn.iocoder.yudao.module.engine.model.context.EngineTimerStatusCacheContext;
import cn.iocoder.yudao.module.engine.model.engine.EngineOutputData;
import cn.iocoder.yudao.module.engine.dal.redis.EngineRedisKeyConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class EngineCacheRedisDAO {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void addOutputAudioCache(Long userId, EngineOutputData.Audio audio) {
        final String lockKey = formatEngineOutputAudioKey(userId);

        final List<String> ids = getOutputAudioCache(userId);
        if (ArrayUtil.isNotEmpty(ids)) {
            // 将audio.getAudioId()拼接到ids中生成1个字符串，多个用逗号隔开
            final StringBuilder stringBuilder = new StringBuilder();
            for (String id : ids) {
                stringBuilder.append(id).append(",");
            }
            stringBuilder.append(audio.getAudioId());

            // 将拼接后的字符串保存到Redis中
            stringRedisTemplate.opsForValue().set(lockKey, stringBuilder.toString());
        } else {
            stringRedisTemplate.opsForValue().set(lockKey, audio.getAudioId());
        }
    }

    public List<String> getOutputAudioCache(Long userId) {
        final String lockKey = formatEngineOutputAudioKey(userId);
        final String ids = stringRedisTemplate.opsForValue().get(lockKey);
        if (StrUtil.isNotEmpty(ids)) {
            final String[] arr = ids.split(",");
            return new ArrayList<>(Arrays.asList(arr));
        }
        return null;
    }

    public void deleteOutputAudioCache(Long userId) {
        final String lockKey = formatEngineOutputAudioKey(userId);
        stringRedisTemplate.delete(lockKey);
    }

    private static String formatEngineOutputAudioKey(Long userId) {
        return String.format(EngineRedisKeyConstants.ENGINE_OUTPUT_AUDIO, userId);
    }

    //////////////////////////////////////// syn status

    public void addEngineSynStatusCache(String gameMatchId, EngineSynStatusCacheContext cacheContext) {
        final String lockKey = formatEngineSynStatusCacheKey(gameMatchId);
        final String str = JsonUtils.toJsonString(cacheContext);
        stringRedisTemplate.opsForValue().set(lockKey, str, 60, TimeUnit.MINUTES);
        log.info("存储引擎同步状态, matchId = {}, value = {}", gameMatchId, str);
    }

    public EngineSynStatusCacheContext getEngineSynStatusCache(String gameMatchId, EngineCacheRedisDAO engineCacheRedisDAO) {
        final String lockKey = formatEngineSynStatusCacheKey(gameMatchId);
        final String str = stringRedisTemplate.opsForValue().get(lockKey);
        if (StrUtil.isNotEmpty(str)) {
            final EngineSynStatusCacheContext ctx = JsonUtils.parseObject(str, EngineSynStatusCacheContext.class);
            ctx.setGameMatchId(gameMatchId);
            ctx.setEngineCacheRedisDAO(engineCacheRedisDAO);
            return ctx;
        }
        return new EngineSynStatusCacheContext(gameMatchId, engineCacheRedisDAO);
    }

    private static String formatEngineSynStatusCacheKey(String gameMatchId) {
        return String.format(EngineRedisKeyConstants.ENGINE_SYN_STATUS, gameMatchId);
    }

    //////////////////////////////////////// timer status

    public void addEngineTimerStatusCache(String gameMatchId, EngineTimerStatusCacheContext timerStatus) {
        final String lockKey = formatEngineTimerStatusCacheKey(gameMatchId);
        final String str = JsonUtils.toJsonString(timerStatus);
        stringRedisTemplate.opsForValue().set(lockKey, str, 60, TimeUnit.MINUTES);
        log.info("存储引擎定时任务状态, matchId = {}, value = {}", gameMatchId, str);
    }

    public EngineTimerStatusCacheContext getEngineTimerStatusCache(String gameMatchId, EngineCacheRedisDAO engineCacheRedisDAO) {
        final String lockKey = formatEngineTimerStatusCacheKey(gameMatchId);
        final String str = stringRedisTemplate.opsForValue().get(lockKey);
        if (StrUtil.isNotEmpty(str)) {
            final EngineTimerStatusCacheContext ctx = JsonUtils.parseObject(str, EngineTimerStatusCacheContext.class);
            ctx.setGameMatchId(gameMatchId);
            ctx.setEngineCacheRedisDAO(engineCacheRedisDAO);
            return ctx;
        }
        return new EngineTimerStatusCacheContext(gameMatchId, engineCacheRedisDAO);
    }

    private static String formatEngineTimerStatusCacheKey(String gameMatchId) {
        return String.format(EngineRedisKeyConstants.ENGINE_TIMER_STATUS, gameMatchId);
    }
}
